package com.auction.service.impl;

import com.auction.dto.AuctionDTO;
import com.auction.dto.AuctionPageQueryDTO;
import com.auction.exception.BusinessException;
import com.auction.mapper.AuctionMapper;
import com.auction.mapper.BidMapper;
import com.auction.mapper.CategoryMapper;
import com.auction.mapper.UserMapper;
import com.auction.pojo.Auction;
import com.auction.pojo.Bid;
import com.auction.pojo.AuctionCategory;
import com.auction.pojo.User;
import com.auction.pojo.PageResult;
import com.auction.service.AuctionService;
import com.auction.vo.AuctionVO;
import com.auction.vo.AuctionDetailVO;
import com.auction.websocket.WebSocketServer;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class AuctionServiceImpl implements AuctionService {

    @Autowired
    private AuctionMapper auctionMapper;

    /**
     * 分页查询拍卖品列表
     *
     * @param auctionPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(AuctionPageQueryDTO auctionPageQueryDTO) {
        // 分页查询
        PageHelper.startPage(auctionPageQueryDTO.getPage(), auctionPageQueryDTO.getPageSize());

        // 查询拍卖品列表
        Page<Auction> page = auctionMapper.pageQuery(auctionPageQueryDTO);

        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 获取拍卖品详情
     *
     * @param id
     * @return
     */
    @Override
    public AuctionVO getByIdVO(Long id) {
        // 获取拍卖品详情
        AuctionVO auctionVO = auctionMapper.selectVOById(id);

        // 验证拍卖品是否存在
        if (auctionVO == null) {
            throw new BusinessException("拍卖品不存在");
        }

        return auctionVO;
    }

    /**
     * 审核拍卖品
     *
     * @param id     拍卖品ID
     * @param status 审核状态（APPROVED-通过，REJECTED-拒绝）
     * @return 是否审核成功
     */
    @Override
    @Transactional
    public boolean reviewAuction(Long id, String status) {

        // 更新拍卖品状态
        int rows = auctionMapper.updateStatus(id, status);
        // 检查更新是否成功
        if (rows <= 0) {
            log.warn("未找到拍卖品，更新失败，拍卖品ID：{}，状态：{}", id, status);
            return false;
        }

        log.info("审核拍卖品，拍卖品ID：{}，状态：{}", id, status);

        return rows > 0;
    }

    /**
     * 根据分类id查询拍卖品列表
     * 
     * @param categoryId
     * @return
     */
    @Override
    public List<AuctionVO> list(Long categoryId) {
        return auctionMapper.list(categoryId);
    }

    /**
     * 发布拍卖品
     * 
     * @param auctionDTO
     * @param sellerId
     * @return
     */
    @Override
    @Transactional
    public void publish(AuctionDTO auctionDTO, Long sellerId) {
        // 创建拍卖品对象
        Auction auction = new Auction();
        BeanUtils.copyProperties(auctionDTO, auction);

        // 设置卖家ID
        auction.setSellerId(sellerId);

        // 设置初始参数
        auction.setStatus("PENDING"); // 待审核状态
        auction.setCreateTime(LocalDateTime.now());
        auction.setUpdateTime(LocalDateTime.now());

        // 插入数据库
        auctionMapper.insert(auction);

        log.info("发布拍卖品成功，ID：{}", auction.getId());
    }

    /**
     * 更新拍卖品
     * 
     * @param auctionDTO
     * @param sellerId
     */
    @Override
    @Transactional
    public void update(AuctionDTO auctionDTO, Long sellerId) {
        // 获取拍卖品信息
        Auction auction = auctionMapper.selectById(auctionDTO.getId());

        // 验证拍卖品是否存在
        if (auction == null) {
            throw new BusinessException("拍卖品不存在");
        }

        // 验证是否为该拍卖品的卖家
        if (!auction.getSellerId().equals(sellerId)) {
            throw new BusinessException("无权操作该拍卖品");
        }

        // 验证拍卖品状态是否可以更新
        if (!"PENDING".equals(auction.getStatus()) && !"ACTIVE".equals(auction.getStatus())) {
            throw new BusinessException("当前状态无法更新拍卖品");
        }

        // 更新拍卖品信息
        BeanUtils.copyProperties(auctionDTO, auction);
        auction.setUpdateTime(LocalDateTime.now());
        auction.setStatus("PENDING"); // 更新后重新变为待审核状态

        // 更新到数据库
        auctionMapper.update(auction);

        log.info("更新拍卖品成功，ID：{}", auction.getId());
    }

    /**
     * 取消拍卖
     * 
     * @param id
     * @param sellerId
     */
    @Override
    @Transactional
    public void cancel(Long id, Long sellerId) {
        // 获取拍卖品信息
        Auction auction = auctionMapper.selectById(id);

        // 验证拍卖品是否存在
        if (auction == null) {
            throw new BusinessException("拍卖品不存在");
        }

        // 验证是否为该拍卖品的卖家
        if (!auction.getSellerId().equals(sellerId)) {
            throw new BusinessException("无权操作该拍卖品");
        }

        // 验证拍卖品状态是否可以取消
        if (!"ACTIVE".equals(auction.getStatus()) && !"PENDING".equals(auction.getStatus())) {
            throw new BusinessException("当前状态无法取消拍卖");
        }

        // 更新拍卖品状态为已取消
        auction.setStatus("CANCELLED");
        auction.setUpdateTime(LocalDateTime.now());

        // 更新到数据库
        auctionMapper.update(auction);

        log.info("取消拍卖成功，ID：{}", id);
    }

    /**
     * 删除拍卖品
     *
     * @param id
     * @param sellerId
     */
    @Override
    public void delete(Long id, Long sellerId) {
        // 获取拍卖品信息
        Auction auction = auctionMapper.selectById(id);

        // 验证拍卖品是否存在
        if (auction == null) {
            throw new BusinessException("拍卖品不存在");
        }

        // 验证是否为该拍卖品的卖家
        if (!auction.getSellerId().equals(sellerId)) {
            throw new BusinessException("无权操作该拍卖品");
        }

        // 验证拍卖品状态是否可以删除
        if (!"ACTIVE".equals(auction.getStatus()) && !"PENDING".equals(auction.getStatus())) {
            throw new BusinessException("当前状态无法删除拍卖品");
        }

        // 删除拍卖品
        auctionMapper.delete(id);

        log.info("删除拍卖品成功，ID：{}", id);
    }

    /**
     * 根据ID获取拍卖品
     *
     * @param id 拍卖品ID
     * @return 拍卖品信息
     */
    @Override
    public Auction getById(Long id) {
        return auctionMapper.selectById(id);
    }
}